import { reactive, toRefs, watch } from 'vue'
import { getPrototypeMethods } from '@/utils'
import { DiyStore } from '@/entity/DiyStore'
import type { IDiyBase } from '@/diy/types'

export const useDiyStore = <T extends DiyStore>(Store: new () => T) => {
  const instance = new Store()
  const state = reactive<T>({ ...instance })
  const actions = getPrototypeMethods(instance)

  watch(
    () => state.currentComponent,
    (value: any, oldValue: any) => {
      //当修改currentComponent的值时，需要改变pageData里相应的值
      if (value && oldValue) {
        const index = state.previewData.pageData.findIndex((el: IDiyBase) => el.id === value.id)
        if (index >= 0) {
          state.previewData.pageData.splice(index, 1, value)
        }
      }
    },
    {
      immediate: true,
      deep: true
    }
  )

  return {
    ...toRefs(state),
    ...actions
  } as any
}
